<template>
  <div v-if="organizationsPage" class="w-75 m-auto mt-4">
    <div class="d-flex flex-row justify-content-between">
      <PaginationBar
        :currentPage="currentPage"
        :lastPage="organizationsPage.pages"
        urlBase="/users/"
      ></PaginationBar>
      <i
        class="bi bi-plus-square fs-3 text-primary"
        data-bs-toggle="modal"
        data-bs-target="#organizationModal"
      ></i>

      <div
        class="modal fade"
        id="organizationModal"
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">
                Добавить компанию
              </h5>
            </div>
            <div class="modal-body">
              <form v-if="tokens">
                <div class="mb-3">
                  <label for="field1" class="form-label">Название</label>
                  <input
                    type="text"
                    :class="'form-control ' + get_msg_class('name')"
                    id="field1"
                    aria-describedby="emailHelp"
                    v-model="name"
                  />
                  <div class="invalid-feedback">
                    {{ get_msg("name") }}
                  </div>
                </div>
                <div class="mb-3">
                  <label for="field2" class="form-label">ИНН</label>
                  <textarea
                    type="text"
                    :class="'form-control ' + get_msg_class('inn')"
                    id="field2"
                    v-model="inn"
                  ></textarea>
                  <div class="invalid-feedback">
                    {{ get_msg("inn") }}
                  </div>
                </div>
                <h3 class="text-danger">{{ msg }}</h3>
              </form>
            </div>
            <div class="modal-footer">
              <button
                id="close_button"
                type="button"
                class="btn btn-secondary"
                data-bs-dismiss="modal"
              >
                Отмена
              </button>
              <button
                type="button"
                class="btn btn-primary"
                @click="sendForm(tokens.access_token)"
              >
                Отправить
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <TableOranization
      :organizations="organizationsPage.items"
      @filter-update="updateHandler"
    ></TableOranization>
    <vue-basic-alert :duration="500" :closeIn="5000" ref="alert" />
  </div>
  <div v-else class="w-75 m-auto mt-4">
    <h3 class="text-danger">{{ error }}</h3>
  </div>
</template>
  
<script>
import TableOranization from "../components/TableOrganization.vue";
import PaginationBar from "../components/PaginationBar.vue";
import { useFetch } from "@vueuse/core";
import VueBasicAlert from "vue-basic-alert";

export default {
  components: {
    TableOranization,
    PaginationBar,
    VueBasicAlert,
  },
  props: {
    tokens: Object,
    user: Object,
    currentPage: Number,
  },
  data() {
    return {
      organizationsPage: undefined,
      error: "",
      filterParams: {
        page: this.currentPage,
        size: 10,
        sort: "desc",
      },
      name: "",
      inn: "",
      msg: "",
      detail: [],
    };
  },
  mounted() {
    this.getPage(this.url, this.tokens.access_token);
  },
  watch: {
    // whenever question changes, this function will run
    currentPage(newCurrentPage) {
      this.filterParams.page = newCurrentPage;
      this.getPage(this.url, this.tokens.access_token);
    },
  },
  methods: {
    get_msg_class(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = "is-invalid";
        }
      });
      return ans;
    },
    get_msg(name) {
      let ans = "";
      this.detail.forEach((el) => {
        if (el.loc[1] == name) {
          ans = el.msg;
        }
      });
      return ans;
    },
    sendForm(token) {
      this.detail = [];
      fetch(`${process.env.VUE_APP_BASE_URI}/organization/create`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: this.name,
          inn: this.inn,
        }),
      }).then(
        (resp) => {
          if (resp.status != 500) {
            resp.json().then(
              (body) => {
                if (resp.ok) {
                  this.detail = [];
                  this.$refs.alert.showAlert(
                    "success",
                    "Вы успешно добавили компанию",
                    "Успех"
                  );
                  this.name = "";
                  this.inn = "";
                  this.getPage(this.url, this.tokens.access_token);
                  document.getElementById("close_button").click();
                } else {
                  this.$refs.alert.showAlert(
                    "error",
                    `${resp.statusText}`,
                    "Ошибка"
                  );
                }
                if (resp.status == 422) {
                  this.detail = body.detail;
                }
              },
              () => {
                this.$refs.alert.showAlert(
                  "error",
                  "Ошибка сервера",
                  "Ошибка обработки json"
                );
              }
            );
          } else {
            this.$refs.alert.showAlert("error", "Ошибка сервера", "500 error");
          }
        },
        (err) => {
          this.$refs.alert.showAlert("error", "Ошибка сервера", err.message);
        }
      );
      // const { isFetching, data, onFetchResponse, onFetchError } = useFetch(
      //   `${process.env.VUE_APP_BASE_URI}/organization/create`,
      //   {
      //     beforeFetch({ options }) {
      //       options.headers.Authorization = `Bearer ${token}`;

      //       return { options };
      //     },
      //   }
      // ).post({
      //   name: this.name,
      //   inn: this.inn,
      // });

      // onFetchResponse(() => {
      //   this.name = "";
      //   this.inn = "";
      //   this.getPage(this.url, this.tokens.access_token);
      //   document.getElementById("close_button").click();
      // });

      // onFetchError((error) => {
      //   this.msg = error.message;
      // });
      // return {
      //   isFetching,
      //   data,
      // };
    },
    // TODO: Добавить логику с фильтрациями, что я реализовал на сервере. В данном случае поиск по теме и по статусу
    getPage(url, token) {
      const { isFetching, data, onFetchError, onFetchResponse } = useFetch(
        url,
        {
          beforeFetch({ options }) {
            options.headers.Authorization = `Bearer ${token}`;

            return { options };
          },
        }
      )
        .get()
        .json();

      onFetchError((error) => {
        this.error = error.message;
      });

      onFetchResponse(() => {
        this.organizationsPage = data.value;
      });
      return { isFetching };
    },
    updateHandler(name, value) {
      console.log(name, value);
      if (value === undefined) {
        delete this.filterParams[name];
      } else {
        this.filterParams[name] = value;
      }
      this.getPage(this.url, this.tokens.access_token);
    },
  },
  computed: {
    url() {
      const _url = new URL(`${process.env.VUE_APP_BASE_URI}/organization/all`);
      _url.search = new URLSearchParams(this.filterParams);
      return _url.toString();
    },
  },
};
</script>
  
<style>
</style>